/*
 * 
 *  This file is part of Sourceprojects.org Thracia.
 *  Copyright 2010 noctarius
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 */
package org.sourceprojects.thracia.output.sender;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Queue;
import java.util.concurrent.SynchronousQueue;

import org.sourceprojects.thracia.ReporterConfig;

/**
 * @author noctarius
 * 
 */
public class ReportSendQueue extends Thread {
	private static final class ReportSendQueueInstanceHolder {
		static final ReportSendQueue INSTANCE = new ReportSendQueue();
	}

	public static final ReportSendQueue getInstance() {
		return ReportSendQueueInstanceHolder.INSTANCE;
	}

	private ReporterConfig config;
	private final Queue<QueuedReport> reportQueue;

	private boolean run = true;

	private ReportSendQueue() {
		reportQueue = new SynchronousQueue<QueuedReport>(true);
	}

	public void addReportToQueue(QueuedReport report) {
		reportQueue.add(report);
	}

	@Override
	public void run() {
		while (run) {
			if (reportQueue.size() > 0) {
				final QueuedReport report = reportQueue.poll();

				if (!sendReport(report)) {
					reportQueue.add(report);
				}
			} else {
				try {
					Thread.sleep(config.getDelay());
				} catch (final InterruptedException e) {
					run = false;
					break;
				}
			}
		}
	}

	private boolean sendReport(QueuedReport report) {
		URL url = null;
		URLConnection connection = null;
		DataOutputStream output = null;
		FileReader reader = null;
		BufferedReader buffer = null;

		try {
			final File file = new File(report.getFilename());
			String xml = "";

			if (file.exists()) {
				return false;
			}

			reader = new FileReader(file);
			buffer = new BufferedReader(reader);

			String line;
			while ((line = buffer.readLine()) != null) {
				xml += line;
			}

			url = new URL("http://" + config.getAddress()
					+ (config.getPort() != 80 ? config.getPort() : "")
					+ "/report");

			connection = url.openConnection();

			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);

			connection.setRequestProperty("Content-Type",
					"text/xml; charset=UTF-8");

			output = new DataOutputStream(connection.getOutputStream());
			output.writeUTF(xml);
			output.flush();
		} catch (final MalformedURLException e) {
			e.printStackTrace();
			return false;
		} catch (final IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (output != null) {
					output.close();
				}

				if (buffer != null) {
					buffer.close();
				}

				if (reader != null) {
					reader.close();
				}
			} catch (final IOException e) {
				e.printStackTrace();
			}
		}

		return true;
	}
}
